<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="申请时间">
              <el-date-picker v-model="queryParams.timeRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审批状态">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option label="待审批" :value="0" />
                <el-option label="审批中" :value="1" />
                <el-option label="已通过" :value="2" />
                <el-option label="已拒绝" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增申购单
      </el-button>
      <el-table :data="orderList" border v-loading="loading" @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column type="selection" align="center" />
        <el-table-column prop="orderNumber" label="申购单号" align="center" />
        <el-table-column prop="applyDate" label="申请时间" align="center" />
        <el-table-column prop="department" label="申请部门" align="center" />
        <el-table-column prop="applicant" label="申请人" align="center" />
        <el-table-column prop="totalQuantity" label="设备数量" align="center" />
        <el-table-column prop="totalAmount" label="总金额(元)" align="center">
          <template #default="{ row }">
            {{ row.totalAmount?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审批状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)" v-if="row.status === 0 || row.status === 1">
              编辑
            </el-button>
            <el-button size="small" type="success" @click="handleApprove(row)" v-if="row.status === 0">
              通过
            </el-button>
            <el-button size="small" type="danger" @click="handleReject(row)" v-if="row.status === 0">
              拒绝
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"
              v-if="row.status === 0 || row.status === 1">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="申请时间" prop="applyDate">
          <el-date-picker v-model="form.applyDate" type="date" placeholder="选择申请时间" value-format="YYYY-MM-DD"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="申请部门" prop="department">
          <el-tree-select v-model="form.department" :data="departmentTree" :value="form.department" :props="treeProps" check-strictly
            node-key="id" :render-after-expand="false" placeholder="请选择申请部门" style="width: 100%" />
        </el-form-item>
        <el-form-item label="申请人" prop="applicant">
          <el-select v-model="form.applicant" placeholder="请选择申请人" style="width: 100%">
            <el-option v-for="employee in employeeList" :key="employee.id" :label="employee.name"
              :value="employee.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请说明" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入申请说明" />
        </el-form-item>

        <el-divider content-position="left">设备清单</el-divider>

        <el-table :data="form.purchaseItemList" border>
          <el-table-column label="设备名称" prop="equipmentName" width="180">
            <template #default="{ row, $index }">
              <el-input v-model="row.equipmentName" placeholder="请输入设备名称" />
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="model" width="150">
            <template #default="{ row, $index }">
              <el-input v-model="row.model" placeholder="请输入规格型号" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="100">
            <template #default="{ row, $index }">
              <el-input-number v-model="row.quantity" :min="1" controls-position="right" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="单价(元)" prop="unitPrice" width="120">
            <template #default="{ row, $index }">
              <el-input-number v-model="row.unitPrice" :min="0" :precision="2" controls-position="right"
                style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="用途说明" prop="purpose">
            <template #default="{ row, $index }">
              <el-input v-model="row.purpose" placeholder="请输入用途说明" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template #default="{ $index }">
              <el-button type="danger" size="small" @click="removePurchaseItem($index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button type="primary" plain @click="addPurchaseItem" style="margin-top: 10px">
          添加设备
        </el-button>

        <el-divider content-position="left">附件</el-divider>

        <el-form-item label="附件">
          <UploadFile v-model:file-ids="form.attachmentIds" :file-list="fileList" v-if="dialog.visible" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`申购单详情 - ${detailDialog.data.orderNumber}`" width="800px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="申购单号">{{ detailDialog.data.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detailDialog.data.applyDate }}</el-descriptions-item>
        <el-descriptions-item label="申请部门">{{ detailDialog.data.department }}</el-descriptions-item>
        <el-descriptions-item label="申请人">{{ detailDialog.data.applicant }}</el-descriptions-item>
        <el-descriptions-item label="设备总数量">{{ detailDialog.data.totalQuantity }}</el-descriptions-item>
        <el-descriptions-item label="预估总金额">{{ detailDialog.data.totalAmount?.toFixed(2) }}元</el-descriptions-item>
        <el-descriptions-item label="审批状态">
          <el-tag :type="getStatusTagType(detailDialog.data.status)">
            {{ getStatusLabel(detailDialog.data.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请说明">{{ detailDialog.data.description || '无' }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">设备清单</el-divider>
      <el-table :data="detailDialog.data.purchaseItemList" border>
        <el-table-column prop="equipmentName" label="设备名称" align="center" />
        <el-table-column prop="model" label="规格型号" align="center" />
        <el-table-column prop="quantity" label="数量" align="center" />
        <el-table-column prop="unitPrice" label="单价(元)" align="center">
          <template #default="{ row }">
            {{ row.unitPrice?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="purpose" label="用途说明" align="center" />
      </el-table>

      <el-divider content-position="left">附件</el-divider>
      <div v-if="detailDialog.data.fileList && detailDialog.data.fileList.length > 0">
        <div v-for="file in detailDialog.data.fileList" :key="file.fileId" class="file-item">
          <el-link :href="file.filePath" target="_blank" type="primary">
            {{ file.originalFileName }}
          </el-link>
        </div>
      </div>
      <div v-else>无附件</div>

      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import UploadFile from '@/components/UploadFile'

import {
  listPurchaseOrder,
  getPurchaseOrderDetail,
  addPurchaseOrder,
  updatePurchaseOrder,
  deletePurchaseOrder,
  auditPurchaseOrder
} from '@/api/prod_operate/device/dev_procure'

// 新增：导入员工和部门接口
import { getEmployeeList, getDeptTree } from '@/api/prod_operate/device/dev_procure'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  timeRange: [],
  startTime: undefined,
  endTime: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  orderNumber: '',
  applyDate: '',
  departmentId: '',      // 改为部门ID
  applicantId: '',       // 改为申请人ID
  description: '',
  purchaseItemList: [],
  attachmentIds: []
})

// 文件列表
const fileList = ref([])

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

const detailDialog = reactive({
  visible: false,
  data: {}
})

// 表格数据
const orderList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()

// 新增：员工列表和部门树数据
const employeeList = ref([])
const departmentTree = ref([])

// 树形选择器配置
const treeProps = {
  children: 'children',
  label: 'label',
  value: 'label'
}

// 表单验证规则
const rules = reactive({
  applyDate: [
    { required: true, message: '请选择申请时间', trigger: 'change' }
  ],
  departmentId: [
    { required: true, message: '请选择申请部门', trigger: 'change' }
  ],
  applicantId: [
    { required: true, message: '请选择申请人', trigger: 'change' }
  ],
  purchaseItemList: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少添加一个设备'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    0: 'warning', // 待审批
    1: 'info',    // 审批中
    2: 'success', // 已通过
    3: 'danger'   // 已拒绝
  }
  return map[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const map = {
    0: '待审批',
    1: '审批中',
    2: '已通过',
    3: '已拒绝'
  }
  return map[status] || '未知状态'
}

// 新增：获取员工列表
const fetchEmployeeList = async () => {
  try {
    const { data } = await getEmployeeList()
    employeeList.value = data || []
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  }
}

// 新增：获取部门树
const fetchDepartmentTree = async () => {
  try {
    const { data } = await getDeptTree()
    departmentTree.value = data || []
  } catch (error) {
    console.error('获取部门树失败:', error)
    ElMessage.error('获取部门树失败')
  }
}

// 获取申购单列表
const fetchOrderList = async () => {
  try {
    loading.value = true

    // 处理时间范围参数
    if (queryParams.timeRange && queryParams.timeRange.length === 2) {
      queryParams.startTime = queryParams.timeRange[0]
      queryParams.endTime = queryParams.timeRange[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }

    const res = await listPurchaseOrder(queryParams)
    orderList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取申购单列表失败:', error)
    ElMessage.error('获取申购单列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchOrderList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.timeRange = []
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  queryParams.status = undefined
  fetchOrderList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchOrderList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchOrderList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 添加设备项
const addPurchaseItem = () => {
  form.purchaseItemList.push({
    id: undefined,
    orderId: undefined,
    equipmentName: '',
    model: '',
    quantity: 1,
    unitPrice: 0,
    purpose: '',
    createdAt: ''
  })
}

// 移除设备项
const removePurchaseItem = (index) => {
  form.purchaseItemList.splice(index, 1)
}

// 新增按钮
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增申购单'

  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }

  Object.assign(form, {
    id: undefined,
    orderNumber: '',
    applyDate: '',
    departmentId: '',
    applicantId: '',
    description: '',
    purchaseItemList: [],
    attachmentIds: []
  })

  fileList.value = []
}

// 编辑按钮
const handleEdit = async (row) => {
  try {
    const res = await getPurchaseOrderDetail(row.id)
    Object.assign(form, {
      id: res.data.id,
      orderNumber: res.data.orderNumber,
      applyDate: res.data.applyDate,
      departmentId: res.data.departmentId,  // 使用部门ID
      applicantId: res.data.applicantId,    // 使用申请人ID
      description: res.data.description,
      purchaseItemList: res.data.purchaseItemList || [],
      attachmentIds: res.data.fileList?.map(file => file.fileId) || []
    })

    // 设置文件列表
    fileList.value = res.data.fileList?.map(file => ({
      name: file.originalFileName,
      url: file.filePath,
      response: { data: { fileId: file.fileId } }
    })) || []

    dialog.visible = true
    dialog.title = '编辑申购单'
  } catch (error) {
    console.error('获取申购单详情失败:', error)
    ElMessage.error('获取申购单详情失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getPurchaseOrderDetail(row.id)
    detailDialog.data = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取申购单详情失败:', error)
    ElMessage.error('获取申购单详情失败')
  }
}

// 通过审批
const handleApprove = (row) => {
  ElMessageBox.confirm(`确认通过申购单 "${row.orderNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return auditPurchaseOrder({ id: row.id, status: 2 })
  }).then(() => {
    ElMessage.success('操作成功')
    fetchOrderList()
  }).catch(() => { })
}

// 拒绝审批
const handleReject = (row) => {
  ElMessageBox.confirm(`确认拒绝申购单 "${row.orderNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return auditPurchaseOrder({ id: row.id, status: 3 })
  }).then(() => {
    ElMessage.success('操作成功')
    fetchOrderList()
  }).catch(() => { })
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除申购单 "${row.orderNumber}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deletePurchaseOrder(row.id)
  }).then(() => {
    ElMessage.success('删除成功')
    fetchOrderList()
  }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 计算总数量和总金额
    const totalQuantity = form.purchaseItemList.reduce((sum, item) => sum + (item.quantity || 0), 0)
    const totalAmount = form.purchaseItemList.reduce((sum, item) => sum + (item.quantity || 0) * (item.unitPrice || 0), 0)

    // 获取选中的部门名称和员工名称
    const selectedDepartment = findDepartmentName(form.departmentId)
    const selectedEmployee = findEmployeeName(form.applicantId)

    const data = {
      ...form,
      totalQuantity,
      totalAmount,
      departmentName: selectedDepartment,  // 添加部门名称
      applicantName: selectedEmployee      // 添加申请人名称
    }

    console.log('提交数据:', data)

    if (form.id) {
      await updatePurchaseOrder(data)
    } else {
      await addPurchaseOrder(data)
    }

    ElMessage.success('操作成功')
    dialog.visible = false
    fetchOrderList()
  } catch (error) {
    console.error('保存申购单失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data.msg || '保存失败')
    }
  }
}

// 新增：根据部门ID查找部门名称
const findDepartmentName = (departmentId) => {
  const findInTree = (nodes) => {
    for (const node of nodes) {
      if (node.id === departmentId) {
        return node.name
      }
      if (node.children && node.children.length > 0) {
        const result = findInTree(node.children)
        if (result) return result
      }
    }
    return ''
  }
  return findInTree(departmentTree.value)
}

// 新增：根据员工ID查找员工名称
const findEmployeeName = (employeeId) => {
  const employee = employeeList.value.find(emp => emp.id === employeeId)
  return employee ? employee.name : ''
}

// 初始化加载数据
onMounted(() => {
  fetchOrderList()
  fetchEmployeeList()
  fetchDepartmentTree()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.file-item {
  margin: 5px 0;
  padding: 5px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.pre-formatted {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>